<template>
  <div class="register-container">
    <div class="register-card-wrapper">
      <el-card class="register-card">
        <div class="register-header">
          <h2>账号注册</h2>
          <p class="subtitle">创建一个新账号</p>
        </div>

        <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="rules"
            label-position="top"
            status-icon
        >
          <el-form-item prop="account" label="手机号">
            <el-input
                v-model="registerForm.account"
                :prefix-icon="User"
                placeholder="请输入11位手机号"
                clearable
                maxlength="11"
                @input="registerForm.account = registerForm.account.replace(/\D/g, '').slice(0, 11)"
            />
          </el-form-item>

          <el-form-item prop="password" label="密码">
            <el-input
                v-model="registerForm.password"
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入6-20位密码"
                show-password
            />
          </el-form-item>

          <el-form-item prop="confirmPassword" label="确认密码">
            <el-input
                v-model="registerForm.confirmPassword"
                :prefix-icon="Lock"
                type="password"
                placeholder="请再次输入密码"
                show-password
            />
          </el-form-item>

          <el-form-item prop="role" label="身份选择">
            <el-radio-group v-model="registerForm.role">
              <el-radio label="worker">家政人员</el-radio>
              <el-radio label="client">客户</el-radio>
            </el-radio-group>
          </el-form-item>

          <div class="agree-terms">
            <el-checkbox v-model="registerForm.agree">我已阅读并同意<el-link type="primary" :underline="false">服务条款</el-link></el-checkbox>
          </div>

          <el-form-item>
            <el-button
                type="primary"
                :loading="loading"
                class="register-button"
                @click="handleRegister"
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>

        <div class="register-footer">
          <p>已有账号? <el-link type="primary" :underline="false" @click="goToLogin">返回登录</el-link></p>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import {userRegister} from "@/api/login/login.js";

const router = useRouter()
const loading = ref(false)
const registerFormRef = ref(null)

// 表单数据
const registerForm = reactive({
  account: '',
  password: '',
  confirmPassword: '',
  role: 'client',
  agree: false
})

// 验证函数
const validateAccount = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的11位手机号'))
  } else {
    callback()
  }
}

const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度需为6-20位'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const validateAgree = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请阅读并同意服务条款'))
  } else {
    callback()
  }
}

// 验证规则
const rules = reactive({
  account: [
    { required: true, validator: validateAccount, trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择身份', trigger: 'change' }
  ],
  agree: [
    { validator: validateAgree, trigger: 'change' }
  ]
})

// 注册处理
const handleRegister = async () => {
  try {
    // 验证表单
    const valid = await registerFormRef.value.validate()
    if (!valid) return

    loading.value = true

    // 准备请求数据
    const registerData = {
      account: registerForm.account,
      password: registerForm.password,
      role: registerForm.role
    }

    // 发送请求
    const response = await userRegister(registerData)

    // 处理响应
    if (response.data.code === 200) {
      ElMessage.success('注册成功，请登录')
      router.push('/login')
    } else {
      ElMessage.error(response.data.message || '注册失败')
    }
  } catch (error) {
    if (error.response) {
      // 后端返回的错误
      ElMessage.error(error.response.data.message || '注册失败')
    } else if (error.message) {
      // 验证错误
      ElMessage.warning(error.message)
    } else {
      // 其他错误
      ElMessage.error('网络错误，请稍后再试')
    }
  } finally {
    loading.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
/* 保持原有样式不变 */
.register-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('/background.png');  /* 修改为使用背景图片 */
  background-size: cover;  /* 确保图片覆盖整个容器 */
  background-position: center;  /* 图片居中 */
  background-repeat: no-repeat;  /* 不重复图片 */
}

.register-card-wrapper {
  width: 400px;
  max-width: 90%;
}

.register-card {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
}

.subtitle {
  color: #606266;
  font-size: 14px;
}

.register-button {
  width: 100%;
  padding: 12px 0;
  border-radius: 4px;
  margin-top: 10px;
}

.agree-terms {
  margin-bottom: 20px;
}

.register-footer {
  margin-top: 20px;
  text-align: center;
  color: #606266;
  font-size: 14px;
}
</style>